<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 聊天室</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }

        #login-container {
            max-width: 300px;
            margin: 100px auto;
            padding: 30px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        #chat-container {
            display: block;
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
        }

        .chat-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
            margin-bottom: 15px;
        }

        .chat-layout {
            display: flex;
            gap: 20px;
            height: 70vh;
        }

        #online-users {
            width: 200px;
            border-right: 1px solid #eee;
            padding-right: 15px;
            overflow-y: auto;
        }

        #chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        #messages {
            flex: 1;
            padding: 10px;
            overflow-y: auto;
            background-color: #fafafa;
            border-radius: 6px;
            margin-bottom: 15px;
        }

        .message {
            margin-bottom: 10px;
            padding: 8px;
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .message.sent {
            background-color: #e3f2fd;
            margin-left: 20%;
        }
        .message.received {
            margin-right: 20%;
        }

        .user-list-item {
            padding: 8px;
            margin: 5px 0;
            cursor: pointer;
            border-radius: 4px;
            transition: background-color 0.2s;
        }

        .user-list-item:hover {
            background-color: #f0f0f0;
        }

        .user-list-item.selected {
            background-color: #007bff !important;
            color: white;
            font-weight: bold;
        }

        #current-user {
            color: #007bff;
            font-weight: bold;
        }

        /* 消息发送区域样式 */
        .send-area {
            border-top: 1px solid #eee;
            padding-top: 15px;
        }

        .receiver-info {
            margin-bottom: 10px;
            color: #666;
        }

        .receiver-name {
            color: #007bff;
            font-weight: bold;
        }

        .warning-text {
            color: #ff4444;
        }

        #message-form {
            display: flex;
            gap: 10px;
        }

        #message-input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        button {
            padding: 8px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }
        .unread-badge {
            display: inline-block;
            min-width: 18px;
            height: 18px;
            padding: 0 4px;
            background: #ff4444;
            color: white;
            border-radius: 9px;
            font-size: 12px;
            line-height: 18px;
            text-align: center;
            margin-left: 8px;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 登录界面 -->
    <div id="login-container" v-if="!currentUser">
        <h2 style="text-align: center; margin-bottom: 25px;">欢迎登录</h2>
        <form @submit.prevent="handleLogin">
            <div style="margin-bottom: 15px;">
                <label>用户名：</label>
                <input type="text" v-model="loginForm.username" required style="width: 100%; padding: 8px;">
            </div>
            <div style="margin-bottom: 20px;">
                <label>密码：</label>
                <input type="password" v-model="loginForm.password" required style="width: 100%; padding: 8px;">
            </div>
            <button type="submit" style="width: 100%;">登 录</button>
        </form>
    </div>

    <!-- 聊天主界面 -->
    <div id="chat-container" v-else>
        <div class="chat-header">
            <h2>聊天室</h2>
            <div>当前用户：<span id="current-user">{{ currentUser }}</span></div>
        </div>

        <div class="chat-layout">
            <!-- 在线用户列表 -->
            <div id="online-users">
                <h3 style="margin-top: 0;">在线用户</h3>
                <ul id="user-list" style="list-style: none; padding: 0; margin: 0;">
                    <li v-for="user in filteredUsers"
                        :key="user"
                        :class="['user-list-item', { 'selected': user === selectedReceiver }]"
                        @click="selectUser(user)"> <!-- 修改点击事件 -->
                        {{ user }}
                        <!-- 添加小红点 -->
                        <span v-if="unreadMessagesCount[user] > 0" class="unread-badge">
        {{ unreadMessagesCount[user] }}
    </span>
                    </li>
                </ul>
            </div>

            <!-- 聊天区域 -->
            <div id="chat-area">
                <div id="messages">
                    <div v-for="(msg, index) in messages"
                         :key="index"
                         :class="['message',{ 'sent': msg.isSent, 'received': !msg.isSent }]">
                        <div style="color: #666; font-size: 0.9em;">
                            {{ msg.time }}
                        </div>
                        <div>{{ msg.content }}</div>
                    </div>
                </div>

                <!-- 消息发送区域 -->
                <div class="send-area">
                    <div v-if="selectedReceiver" class="receiver-info">
                        正在发送给：<span class="receiver-name">{{ selectedReceiver }}</span>
                    </div>
                    <div v-else class="receiver-info warning-text">
                        请从左侧用户列表选择接收人
                    </div>

                    <form @submit.prevent="sendMessage" id="message-form">
                        <input type="text"
                               id="message-input"
                               v-model="messageInput"
                               placeholder="输入消息..."
                               autocomplete="off"
                               @keypress.enter.prevent="sendMessage">
                        <button type="submit">发送</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                loginForm: {
                    username: '',
                    password: ''
                },
                currentUser: '',
                onlineUsers: [],
                messages: [],
                websocket: null,
                selectedReceiver: '',
                messageInput: '',
                unreadMessagesCount: {} // 新增未读消息计数
            }
        },
        computed: {
            filteredUsers() {
                return this.onlineUsers.filter(user => user !== this.currentUser)
            }
        },
        watch: {
            selectedReceiver(newVal) {
                if (newVal) {
                    this.fetchHistory()
                    this.scrollToBottom()
                }
            }
        },
        methods: {
            async handleLogin() {
                if (!this.loginForm.username || !this.loginForm.password) {
                    alert('请输入用户名和密码')
                    return
                }

                try {
                    const response = await fetch('/login', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            userName: this.loginForm.username,
                            password: this.loginForm.password
                        }),
                        credentials: 'include'
                    })

                    if (response.ok) {
                        const data = await response.json()
                        if (data.code == 200) {
                            this.currentUser = this.loginForm.username
                            this.initWebSocket()
                        } else {
                            alert('登录: ' + (data.msg || '未知错误'))
                        }
                    } else {
                        alert('登录失败，状态码：' + response.status)
                    }
                } catch (error) {
                    console.error('登录错误:', error)
                    alert('网络请求失败，请检查控制台')
                }
            },

            initWebSocket() {
                const wsUri = `ws://${location.host}/websocket`
                this.websocket = new WebSocket(wsUri)

                this.websocket.onopen = () => {
                    this.heartbeatTimer = setInterval(() => {
                        if (this.websocket.readyState === WebSocket.OPEN) {
                            this.websocket.send(new Uint8Array([]))
                        }
                    }, 30000)
                }

                this.websocket.onmessage = (event) => {
                    try {
                        let users;
                        if (event.data.startsWith('[') && event.data.endsWith(']')) {
                            users = event.data
                                .slice(1, -1)
                                .split(',')
                                .map(user => user.trim().replaceAll('"', ''));
                        } else {
                            users = JSON.parse(event.data);
                        }

                        if (Array.isArray(users)) {
                            this.onlineUsers = users;
                            this.$forceUpdate();
                            return;
                        }
                        throw new Error('无效的用户列表格式');
                    } catch (e) {
                        const data = event.data;
                        const colonIndex = data.indexOf(':');
                        let sender = colonIndex !== -1
                            ? data.substring(0, colonIndex)
                            : 'System'; // 默认发送者

                        // 如果当前不是该发送者的聊天页面
                        if (sender !== this.selectedReceiver) {
                            // 使用 Vue.set 确保响应式更新
                            this.$set(this.unreadMessagesCount, sender,
                                (this.unreadMessagesCount[sender] || 0) + 1
                            );
                        }

                        // 如果是当前聊天对象的消息，直接显示
                        if (sender === this.selectedReceiver) {
                            this.addMessage({
                                content: data,
                                isSent: false,
                                time: new Date().toLocaleTimeString()
                            });
                        }
                    }
                };

                this.websocket.onerror = (error) => {
                    console.error('WebSocket错误:', error)
                    alert('连接发生错误，请刷新页面重试')
                }

                this.websocket.onclose = (event) => {
                    console.log('连接关闭:', event)
                    if (event.code === 1002) {
                        alert('协议错误，请更新浏览器版本或联系管理员')
                    }
                }
            },
            selectUser(user) {
                // 切换选中用户
                this.selectedReceiver = user;

                // 重置该用户的未读计数
                this.$set(this.unreadMessagesCount, user, 0);

            },
            // 异步获取历史记录
            async fetchHistory() {
                // 如果没有选择接收者或者正在加载历史记录，则返回
                if (!this.selectedReceiver) return
                this.messages = [];

                try {
                    // 发送POST请求获取历史记录
                    const response = await fetch('/getContent', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({
                            fromName: this.currentUser,
                            toName: this.selectedReceiver
                        })
                    })

                    // 如果请求成功
                    if (response.ok) {
                        // 解析返回的数据
                        const result = await response.json()
                        console.log("得到记录",result.data)
                        // 如果返回码为200，表示获取历史记录成功
                        if (result.code == 200) {
                            // 转换历史消息格式
                            console.log("进入转换")
                            const historyMessages = result.data.map(msg => ({
                                content:msg.fromName+ ":"+msg.content,
                                time: this.formatTime(msg.createTime),
                                createTime: new Date(msg.createTime).getTime(),
                                fromName: msg.fromName,
                                isSent: msg.fromName === this.currentUser,
                            }))
                            console.log("进入转换：",historyMessages)

                            // 将历史消息和实时消息合并
                            this.messages = [...historyMessages]
                        }
                    }
                } catch (error) {
                    // 如果加载历史记录失败，打印错误信息
                    console.error('加载历史记录失败:', error)
                } },
            formatTime(isoString) {
                const date = new Date(isoString)
                return date.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                })
            },

            addMessage(message) {
                this.messages.push(message)
                this.scrollToBottom()
            } ,

            sendMessage() {
                if (!this.selectedReceiver) {
                    alert('请选择接收人')
                    return
                }

                if (!this.messageInput.trim()) {
                    alert('请输入消息内容')
                    return
                }

                if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
                    const content = `${this.selectedReceiver}:${this.messageInput}`
                    this.websocket.send(content)
                    this.addMessage({
                        content: ` ${this.currentUser}: ${this.messageInput}`,
                        time: new Date().toLocaleTimeString(),
                        isSent: true
                    })
                    this.messageInput = ''
                } else {
                    alert('连接未就绪，请刷新页面重试')
                }
            },

            scrollToBottom() {
                this.$nextTick(() => {
                    const messagesDiv = document.getElementById('messages')
                    if (messagesDiv) {
                        messagesDiv.scrollTop = messagesDiv.scrollHeight
                    }
                })
            }
        },

        beforeDestroy() {
            if (this.websocket) {
                this.websocket.close(1000, '正常关闭');
            }
            clearInterval(this.heartbeatTimer);
        }
    })
</script>
</body>
</html>